import * as toast from '@/util/toast/toast'
export function photoCompression (file:any, Func:any) {
  if (file.file.size > 2000000) {
    toast.showLoading('')
    // 判断图片大于2M就压缩
    const num = Math.sqrt(2000000 / file.file.size) // 获取图片的压缩比例
    const canvas = document.createElement('canvas')
    const context = canvas.getContext('2d')
    const img = new Image()
    img.src = file.content
    img.onload = () => {
      canvas.width = img.width * num // 把上传的图片宽度乘以压缩比例
      canvas.height = img.height * num // 把上传的图片高度乘以压缩比例
      context!.drawImage(img, 0, 0, img.width * num, img.height * num)
      file.content = canvas.toDataURL(file.file.type, 0.92) // 比例传1，也有的传0.92但是感觉压缩得太厉害了
      const files = dataURLtoFile(file.content, file.file.name)
      toast.hideLoading()
      Func(files)
    }
  } else {
    // 当图片小于2M时就正常上传
    Func(file)
  }
}
// 图片压缩方法
export function dataURLtoFile (dataurl:string, filename:string) {
  const arr = dataurl.split(',')
  const mime = arr![0].match(/:(.*?);/)![1]
  const bstr = atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  const file = new File([u8arr], filename, { type: mime })
  const data = { // 拼成你所需要传给后端的格式
    file: file,
    content: dataurl,
    message: '',
    status: ''
  }
  return data
}
